//
//  sdkDemoViewController.m
//  sdkDemo
//
//  Created by qqconnect on 13-3-29.
//  Copyright (c) 2013年 qqconnect. All rights reserved.
//

#import "sdkDemoViewController.h"
#import "sdkDemoAppDelegate.h"
#import "SDKCall.h"
#import "QCellInfo.h"
#import "SDKDemoDefine.h"
#import "QZoneTableViewController.h"
#import "QQApiShareEntry.h"
#import <time.h>
#import <TencentOpenAPI/TencentOAuth.h>
#import <TencentOpenAPI/QQApiInterface.h>

#if !QQ_OPEN_SDK_LITE
#import <TencentOpenAPI/TencentOAuth+Full.h>
#import "QQGroupProViewController.h"
#endif

#import <MediaPlayer/MediaPlayer.h>
#import <MobileCoreServices/MobileCoreServices.h>
#import <CommonCrypto/CommonDigest.h>
#import "FeaturesTableViewController.h"

#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Warc-performSelector-leaks"
#pragma GCC diagnostic ignored "-Wundeclared-selector"
#pragma clang diagnostic ignored "-Wobjc-protocol-method-implementation"


typedef NS_ENUM(NSInteger, QQDemoTableViewSectionIndex) {
    QQDemoTableViewSectionIndexLogin,       // 授权登录
#if !QQ_OPEN_SDK_LITE
    QQDemoTableViewSectionIndexProxyLogin,  // 代理登录
#endif
    QQDemoTableViewSectionIndexToken,       // token管理
    QQDemoTableViewSectionIndexAPI,         // 互联API，分享、建群、频道、空间
    QQDemoTableViewSectionIndexStatus,      // 当前状态
    QQDemoTableViewSectionIndexCount        // index总数 count
};
typedef NS_ENUM(NSInteger, QQDemoTableViewSectionOfStatusRowIndex) {
    QQDemoTableViewSectionOfStatusRowIndexCurrentStatus,            // 当前授权等状态信息
    QQDemoTableViewSectionOfStatusRowIndexUserAgreeAuthorization,   // 用户是否同意协议
    QQDemoTableViewSectionOfStatusRowIndexCount                     // index总数 count
};

@implementation sdkDemoNavgationController

- (BOOL)shouldAutorotate
{
    return BOOL_SHOULD_AUTORATE;
}

#if __IPHONE_OS_VERSION_MAX_ALLOWED < 90000
- (NSUInteger)supportedInterfaceOrientations
#else
- (UIInterfaceOrientationMask)supportedInterfaceOrientations
#endif
{
    return Supported_Interface_Orientations;
}

@end

@interface sdkDemoViewController ()
{
    FGalleryViewController  *_localGallery;
    NSInteger               _currentTableViewTag;
    time_t                  loginTime;
    NSTimeInterval _consume_getuserinfo;
}

@property (nonatomic, strong) NSMutableArray *sectionName;
@property (nonatomic, strong) NSMutableArray *sectionRow;

@property (nonatomic, copy) NSDictionary *userInfo;

@property (nonatomic, strong) UIImageView *avatarView;
@property (nonatomic, strong) UILabel *nickLabel;
@property (nonatomic, assign) BOOL needShowUserInfoView;

@end

@implementation sdkDemoViewController

@synthesize sectionName = _sectionName;
@synthesize sectionRow = _sectionRow;

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self)
    {
        // Custom initialization
        self.sectionName = [NSMutableArray arrayWithCapacity:1];
        self.sectionRow = [NSMutableArray arrayWithCapacity:1];
        [self loadData];
        _isLogined = NO;
        _currentTableViewTag = 0;
        loginTime = 0;
    }

    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    NSString *version = [NSString stringWithFormat:@"%@.%@",
                         [TencentOAuth sdkVersion], [TencentOAuth sdkSubVersion]];
    
    UIView *leftCustomView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 200.0, 44.0)];
    [leftCustomView addSubview:self.avatarView];
    [leftCustomView addSubview:self.nickLabel];
    UIBarButtonItem *leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:leftCustomView];
    self.navigationItem.leftBarButtonItem = leftBarButtonItem;
    
    UIBarButtonItem *rightButton = [[UIBarButtonItem alloc] initWithTitle:version style:UIBarButtonItemStylePlain target:self action:@selector(rightButtonAction)];
    self.navigationItem.rightBarButtonItem = rightButton;
}

- (void)rightButtonAction {
    
}

- (void)loadData
{
    // 登录相关， QQDemoTableViewSectionIndexLogin
    NSMutableArray *cellLogin = [NSMutableArray arrayWithCapacity:1];
    [cellLogin addObject:[QCellInfo info:@"第三方登录" target:self Sel:@selector(authorizedLogin) viewController:nil]];
    [cellLogin addObject:[QCellInfo info:@"第三方扫码登录" target:self Sel:@selector(loginWithQRlogin) viewController:nil]];
    [cellLogin addObject:[QCellInfo info:@"第三方扫码登录(强制)" target:self Sel:@selector(forceLoginWithQRLogin) viewController:nil]];
    [cellLogin addObject:[QCellInfo info:@"退出账号" target:self Sel:@selector(logout) viewController:nil]];
    [[self sectionName] addObject:@"登录相关"];
    [[self sectionRow] addObject:cellLogin];
    
    // 代理登录， QQDemoTableViewSectionIndexProxyLogin
#if !QQ_OPEN_SDK_LITE
    NSMutableArray* proxyLogin = [NSMutableArray new];
    [proxyLogin addObject:[QCellInfo info:@"代理登录" target:self Sel:@selector(proxyLogin) viewController:nil]];
    [[self sectionName] addObject:@"代理登录"];
    [[self sectionRow] addObject:proxyLogin];
#endif
    
    // token管理，QQDemoTableViewSectionIndexToken
    NSMutableArray *tokenArr = [NSMutableArray array];
    [tokenArr addObject:[QCellInfo info:@"查看缓存Token" target:self Sel:@selector(viewCachedToken) viewController:nil]];
    [tokenArr addObject:[QCellInfo info:@"删除缓存Token" target:self Sel:@selector(deleteCachedToken) viewController:nil]];
    [[self sectionName] addObject:@"Token"];
    [[self sectionRow] addObject:tokenArr];
    
    // 互联API，分享、建群、频道、空间， QQDemoTableViewSectionIndexAPI
    NSMutableArray *cellApiInfo = [NSMutableArray arrayWithCapacity:4];
    [cellApiInfo addObject:[QCellInfo info:@"QQ分享" target:nil Sel:@selector(pushSelectedViewController:) viewController:nil userInfo:[NSNumber numberWithInteger:kApiQQ]]];
    [cellApiInfo addObject:[QCellInfo info:@"QQ空间" target:self Sel:@selector(pushSelectedViewController:) viewController:nil userInfo:[NSNumber numberWithInteger:kApiQZone]]];
    [cellApiInfo addObject:[QCellInfo info:@"UnionID" target:nil Sel:@selector(RequestUnionId) viewController:nil userInfo:nil]];
#if OPEN_API_GROUP
    [cellApiInfo addObject:[QCellInfo info:@"QQ群" target:nil Sel:@selector(pushSelectedViewController:) viewController:nil userInfo:[NSNumber numberWithInteger:kApiQQqun]]];
#endif
#if !QQ_OPEN_SDK_LITE
    [cellApiInfo addObject:[QCellInfo info:@"QQ频道" target:nil Sel:@selector(pushSelectedViewController:) viewController:nil userInfo:[NSNumber numberWithInteger:kApiQQGroupPro]]];
#endif
    [cellApiInfo addObject:[QCellInfo info:@"QQ支持能力" target:nil Sel:@selector(pushSelectedViewController:) viewController:nil userInfo:[NSNumber numberWithInteger:kApiQQFeatures]]];
    [[self sectionName] addObject:@"api"];
    [[self sectionRow] addObject:cellApiInfo];
    
    // 当前状态信息， QQDemoTableViewSectionIndexStatus
    NSMutableArray *appInfoCell = [NSMutableArray arrayWithCapacity:3];
    [appInfoCell addObject:[QCellInfo info:@"当前状态信息" target:nil Sel:@selector(showDemoAppStatus) viewController:nil userInfo:nil]];
    [appInfoCell addObject:[QCellInfo info:@"是否同意隐私协议（点击同意/取消）" target:nil Sel:@selector(setIsUserAgreeAhthorization) viewController:nil userInfo:nil]];
    [[self sectionName] addObject:@"状态信息"];
    [[self sectionRow] addObject:appInfoCell];

    // 添加相关通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loginSuccessedNotification:) name:kLoginSuccessed object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loginFailedNotification:) name:kLoginFailed object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loginCannelledNotification:) name:kLoginCancelled object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didGetUnionIDNotification:) name:kGetUnionID object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(logoutSuccessedNotification:) name:kLogoutSuccessed object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getUserInfoSuccessedNotification:) name:kGetUserInfoResponse object:nil];
    
    // 互联SDK初始化
    [SDKCall getinstance];
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    self.albumId = nil;
    self.sectionName = nil;
    self.sectionRow = nil;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return [[self sectionName] count];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [[[self sectionRow] objectAtIndex:section] count];
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    return [[self sectionName] objectAtIndex:section];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSUInteger row = [indexPath row];
    NSUInteger section = [indexPath section];
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellSelectionStyleNone reuseIdentifier:CellIdentifier];
    }
    
    NSString *title = nil;
    NSMutableArray *array = [[self sectionRow] objectAtIndex:section];
    if ([array isKindOfClass:[NSMutableArray class]]) {
        title = [[array objectAtIndex:row] title];
    }
    if (nil == title) {
        title = @"未知";
    }
    
    [[cell textLabel] setText:title];
    [[cell textLabel] setTextAlignment:NSTextAlignmentCenter];
    cell.accessoryType = UITableViewCellAccessoryDetailDisclosureButton;
    if (section == QQDemoTableViewSectionIndexStatus && row == QQDemoTableViewSectionOfStatusRowIndexUserAgreeAuthorization) {
        BOOL isUserAgreedAuthorization = [self isUserAgreedAuthorization];
        cell.accessoryType = isUserAgreedAuthorization ? UITableViewCellAccessoryCheckmark : UITableViewCellAccessoryNone;
    }
    
    return cell;
}

#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath {
    [self onTapAtIndexPath:indexPath];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    [self onTapAtIndexPath:indexPath];
    [[tableView cellForRowAtIndexPath:indexPath] setHighlighted:NO animated:NO];
}

- (void)onTapAtIndexPath:(NSIndexPath *)indexPath {
    NSInteger row = [indexPath row];
    NSInteger section = [indexPath section];
    
    NSArray *array = [[self sectionRow] objectAtIndex:section];
    if ([array isKindOfClass:[NSMutableArray class]])
    {
        QCellInfo *info = (QCellInfo *)[array objectAtIndex:row];
        if ([self respondsToSelector:[info sel]])
        {
            if (nil == [info userInfo])
            {
                [self performSelector:[info sel]];
            }
            else
            {
                [self performSelector:[info sel] withObject:[info userInfo]];
            }
        }
    }
}

#pragma mark - Notification Methods

- (void)loginSuccessedNotification:(NSNotification *)notification
{
    if (NO == _isLogined)
    {
        _isLogined = YES;
    }
    
    NSString *result = nil;
    if ([TencentOAuth sharedInstance].authMode == kAuthModeServerSideCode ) {
        result = [NSString stringWithFormat:@"登录成功 passData = \n %@,\n%@ = %@",
                  [[TencentOAuth sharedInstance] passData],
                  @"Sever Code",
                  [TencentOAuth sharedInstance].accessToken];
    } else {
        result = [NSString stringWithFormat:@"登录成功 passData = \n %@,\n%@ = %@, openid = %@",
                            [[TencentOAuth sharedInstance] passData],
                            @"Client Token",
                            [TencentOAuth sharedInstance].accessToken,
                            [TencentOAuth sharedInstance].openId];
    }
    
    NSString *resultTitle = [NSString stringWithFormat:@"登录结果(%@)", ([TencentOAuth sharedInstance].authMode == kAuthModeServerSideCode ? @"Server Code" : @"Client Token")];
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:resultTitle message:result delegate:nil cancelButtonTitle:@"好的" otherButtonTitles:nil];
    [alertView show];
    
#if !QQ_OPEN_SDK_LITE
    if ([[TencentOAuth sharedInstance] proxyAuthResp]) {
        NSLog(@"proxyAuthResp:%@", [[TencentOAuth sharedInstance] proxyAuthResp].description);
    }
#endif
    
    [self insertGetUserInfoCell];
    
    self.needShowUserInfoView = NO;
    [self getUserInfo];
}

- (void)loginFailedNotification:(NSNotification *)notification
{
    [self handleLoginFaild];
}

- (void)loginCannelledNotification:(NSNotification *)notification
{
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"结果" message:@"取消登录" delegate:nil cancelButtonTitle:@"好的" otherButtonTitles:nil];
    [alertView show];
}

- (void)didGetUnionIDNotification:(NSNotification *)notification {
    NSString *result  = [NSString stringWithFormat:@"获取成功，结果已经复制到粘贴板。\n appid = %@,\n openid = %@,\n unionid = %@",
                         [[TencentOAuth sharedInstance] appId],
                         [TencentOAuth sharedInstance].openId,
                         [TencentOAuth sharedInstance].unionid];
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:result delegate:nil cancelButtonTitle:@"好的" otherButtonTitles:nil];
    [[UIPasteboard generalPasteboard] setString:result];
    [alertView show];
}

- (void)logoutSuccessedNotification:(NSNotification *)notification
{
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"结果" message:@"已退出登录" delegate:nil cancelButtonTitle:@"好的" otherButtonTitles:nil];
    [alertView show];
}

- (void)refreshNavigationBar:(NSDictionary *)userInfo {
    self.nickLabel.text = userInfo[@"nickname"];
    dispatch_async(dispatch_get_main_queue(), ^{
        UIImage *image = [self imageWithUrl: userInfo[@"figureurl_2"]];
        if (!image) {
            return;
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            self.avatarView.image = image;
        });
    });
}

- (void)getUserInfoSuccessedNotification:(NSNotification *)notification
{
    NSDictionary *notificationUserInfo = notification.userInfo;
    APIResponse *response = notificationUserInfo[kResponse];
    NSDictionary *userInfo = response.jsonResponse;
    self.userInfo = userInfo;
    
    [self refreshNavigationBar:userInfo];
    if (!self.needShowUserInfoView) {
        return;
    }
    
    UIView *userInfoView = [[UIView alloc] initWithFrame:CGRectMake(10, 0, self.view.frame.size.width - 10 * 2, 300)];
    userInfoView.backgroundColor = [UIColor colorWithRed:50/255.0 green:50/255.0 blue:50/255.0 alpha:0.8];
    [self.view addSubview:userInfoView];
    userInfoView.tag = 666;
    userInfoView.center = CGPointMake(self.view.frame.size.width / 2.0, self.view.frame.size.height / 2.0 - 80);
    
    //这里用来适配暗色模式下点击“显示用户信息”显示不全问题
    if (@available(iOS 13.0, *)){
        UIUserInterfaceStyle mode = UITraitCollection.currentTraitCollection.userInterfaceStyle;
        if (mode == UIUserInterfaceStyleDark) {
            userInfoView.backgroundColor = [UIColor darkGrayColor];
        } else {
            userInfoView.backgroundColor = [UIColor colorWithRed:50/255.0 green:50/255.0 blue:50/255.0 alpha:0.8];
        }
    }
    
    UIColor *textColor = [UIColor whiteColor];
    UIFont *textFont = [UIFont systemFontOfSize:16];
    
    UILabel *nameLabel = [[UILabel alloc] initWithFrame:CGRectMake(15, 0, userInfoView.width / 2.0 - 15, 50)];
    nameLabel.textAlignment = NSTextAlignmentLeft;
    nameLabel.font = textFont;
    nameLabel.text = [NSString stringWithFormat:@"昵称：%@", userInfo[@"nickname"]];
    nameLabel.textColor = textColor;
    [userInfoView addSubview:nameLabel];
    
    UILabel *gender = [[UILabel alloc] initWithFrame:CGRectMake(userInfoView.width / 2.0, 0, userInfoView.width / 2.0 - 15, 50)];
    gender.textAlignment = NSTextAlignmentLeft;
    gender.font = textFont;
    gender.text = [NSString stringWithFormat:@"性别：%@", userInfo[@"gender"]];
    gender.textColor = textColor;
    [userInfoView addSubview:gender];
    
    UILabel *city = [[UILabel alloc] initWithFrame:CGRectMake(15, 50, userInfoView.width / 2.0 - 15, 50)];
    city.textAlignment = NSTextAlignmentLeft;
    city.font = textFont;
    city.text = [NSString stringWithFormat:@"城市：%@", userInfo[@"city"]];
    city.textColor = textColor;
    [userInfoView addSubview:city];
    
    UILabel *year = [[UILabel alloc] initWithFrame:CGRectMake(userInfoView.width / 2.0, 50, userInfoView.width / 2.0 - 15, 50)];
    year.textAlignment = NSTextAlignmentLeft;
    year.font = textFont;
    year.text = [NSString stringWithFormat:@"出生年份：%@", userInfo[@"year"]];
    year.textColor = textColor;
    [userInfoView addSubview:year];
    
    UIImageView *heardImageView = [[UIImageView alloc] initWithFrame:CGRectMake(15, 120, 80, 80)];
    heardImageView.backgroundColor = [[UIColor blueColor] colorWithAlphaComponent:0.2];
    heardImageView.image = [self imageWithUrl: userInfo[@"figureurl_2"]];
    [userInfoView addSubview:heardImageView];
    
    
    UIImageView *heardImageViewQQ = [[UIImageView alloc] initWithFrame:CGRectMake(userInfoView.width / 2.0, 120, 80, 80)];
    heardImageViewQQ.backgroundColor = [[UIColor blueColor] colorWithAlphaComponent:0.2];
    heardImageViewQQ.image = [self imageWithUrl: userInfo[@"figureurl_qq_2"]];
    [userInfoView addSubview:heardImageViewQQ];
    
    UIButton *closeBtn = [[UIButton alloc] initWithFrame:CGRectMake((userInfoView.width - 100) / 2.0, userInfoView.height - 50 - 40, 100, 50)];
    [closeBtn setTitle:@"关   闭" forState:UIControlStateNormal];
    [closeBtn setTitleColor:textColor forState:UIControlStateNormal];
    [closeBtn addTarget:self action:@selector(closeAction) forControlEvents:UIControlEventTouchDown];
    [userInfoView addSubview:closeBtn];
    
    UIButton *detailButton = [[UIButton alloc] initWithFrame:CGRectMake((userInfoView.width - 100) / 2.0, userInfoView.height - 50, 100, 50)];
    [detailButton setTitle:@"详   情" forState:UIControlStateNormal];
    [detailButton setTitleColor:textColor forState:UIControlStateNormal];
    [detailButton addTarget:self action:@selector(userInfoDetailAction:) forControlEvents:UIControlEventTouchDown];
    [userInfoView addSubview:detailButton];
}

- (void)insertGetUserInfoCell
{
    NSArray *arrayCell = [[self tableView] visibleCells];
    for (id cell in arrayCell)
    {
        [[cell textLabel] setEnabled:_isLogined];
    }
    
    NSMutableArray *cellLogin = self.sectionRow[0];
    QCellInfo* lastOne = cellLogin[cellLogin.count - 1];
    if ([lastOne.title isEqualToString:@"获取个人信息"]) {
        return;
    }
    [cellLogin addObject:[QCellInfo info:@"获取个人信息" target:self Sel:@selector(getUserInfoEvent) viewController:nil]];
    [self.tableView reloadData];
}

- (void)getUserInfoEvent {
    self.needShowUserInfoView = YES;
    [self getUserInfo];
}

- (void)getUserInfo
{
    _consume_getuserinfo = [[NSDate date] timeIntervalSince1970];
    if (![[TencentOAuth sharedInstance] getUserInfo]) {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"结果" message:@"获取用户信息失败" delegate:nil cancelButtonTitle:@"好的" otherButtonTitles:nil];
        [alertView show];
    }
}

- (void)handleLoginFaild
{
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"登录失败" message:@"请查看日志获取相关信息" delegate:nil cancelButtonTitle:@"好的" otherButtonTitles:nil];
    [alertView show];
}

- (UIImage *)imageWithUrl:(NSString *)urlStr
{
    NSURL *url = [NSURL URLWithString:urlStr];
    return [UIImage imageWithData:[NSData dataWithContentsOfURL:url]];
}

- (void)closeAction
{
    UIView *userInfoView = [self.view viewWithTag:666];
    [userInfoView removeFromSuperview];
}

- (void)userInfoDetailAction:(UIButton *)button {
    NSMutableString *message = [NSMutableString string];
    [self.userInfo enumerateKeysAndObjectsUsingBlock:^(id  _Nonnull key, id  _Nonnull obj, BOOL * _Nonnull stop) {
        NSString *value = obj;
        if ([obj isKindOfClass:[NSString class]] && value.length > 15) {
            value = [value substringToIndex:15];
            value = [value stringByAppendingString:@"..."];
        }
        [message appendFormat:@"\n%@: %@", key, value];
    }];
    
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"用户信息" message:message preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *alertAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    [alertController addAction:alertAction];
    
    NSMutableAttributedString *attMsgString = [[NSMutableAttributedString alloc] initWithString:message];
    // 设置字体
    [attMsgString addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:14] range:NSMakeRange(0, attMsgString.length)];
    // 设置颜色
    [attMsgString addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor] range:NSMakeRange(0, 10)];
    NSMutableParagraphStyle *paragraph = [[NSMutableParagraphStyle alloc] init];
    // 设置行间距
    [paragraph setLineSpacing:3];
    // 设置段间距
    [paragraph setParagraphSpacingBefore:5];
    // 设置对齐方式
    [paragraph setAlignment:NSTextAlignmentLeft];
    // 设置书写方向
    [paragraph setBaseWritingDirection:NSWritingDirectionLeftToRight];
    [attMsgString addAttribute:NSParagraphStyleAttributeName value:paragraph range:NSMakeRange(0, attMsgString.length)];
    [alertController setValue:attMsgString forKey:@"attributedMessage"];
    
    [self presentViewController:alertController animated:YES completion:^{
        
    }];
}

#pragma mark - Private Methods

// 授权登录
- (void)authorizedLogin
{
    time_t currentTime;
    time(&currentTime);
    
    if ((currentTime - loginTime) > 2)
    {
        TencentOAuth * oauth = [TencentOAuth sharedInstance];
        oauth.authMode = kAuthModeClientSideToken;
        [oauth authorize:[self getPermissions]];
//        [self askIfSetDefaultUin];
        loginTime = currentTime;
    } else {
        NSLog(@"慢一点，登录太频繁了(2s限频)");
    }
}

- (void)askIfSetDefaultUin {
    TencentOAuth * oauth = [TencentOAuth sharedInstance];
    
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"输入账号(仅调试用)" message:nil preferredStyle:(UIAlertControllerStyleAlert)];
    [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
        
        NSString *default_uin = alert.textFields.firstObject.text;
        oauth.defaultUin = default_uin;
        [oauth authorize:[self getPermissions]];
    }]];
    [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:(UIAlertActionStyleCancel) handler:^(UIAlertAction * _Nonnull action) {
        oauth.defaultUin = nil;
        [oauth authorize:[self getPermissions]];
    }]];
    
    [alert addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
        textField.clearButtonMode = UITextFieldViewModeAlways;
        textField.placeholder = @"输入账号";
        textField.text = @"1104466820";
    }];
    [self presentViewController:alert animated:YES completion:nil];
}

// 扫码登录
- (void)loginWithQRlogin
{
    time_t currentTime;
    time(&currentTime);
    
    if ((currentTime - loginTime) > 2)
    {
        TencentOAuth * oauth = [TencentOAuth sharedInstance];
        oauth.authMode = kAuthModeClientSideToken; // kAuthModeClientSideToken;//kAuthModeServerSideCode;
        //二维码登录
        [oauth authorizeWithQRlogin:[self getPermissions]];
        loginTime = currentTime;
    } else {
        NSLog(@"慢一点，登录太频繁了(2s限频)");
    }
}

// 强制扫码登录
- (void)forceLoginWithQRLogin {
    [SDKCall getinstance].forceWebLogin = YES;
    [self loginWithQRlogin];
    [SDKCall getinstance].forceWebLogin = NO;
}

// 代理登录
#if !QQ_OPEN_SDK_LITE
- (void)proxyLogin {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"设置代理AppId" message:nil preferredStyle:(UIAlertControllerStyleAlert)];
    [alert addAction:[UIAlertAction actionWithTitle:@"设置" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
        
        NSString *appid = alert.textFields.firstObject.text;
        TencentOAuth * oauth = [TencentOAuth sharedInstance];
        NSDictionary *extraParam = @{
            @"clientage_token" : @"clientage_token_wallejlchen",
        };
        BOOL ret = [oauth proxyAuthorize:appid permissions:[self getProxyPermissioins] extraParams:extraParam state:@"2020-04-16 cocozzhang"];
        if (!ret) {
            [self handleLoginFaild];
        }
    }]];
    [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:(UIAlertActionStyleCancel) handler:nil]];
    
    [alert addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
        textField.clearButtonMode = UITextFieldViewModeAlways;
        textField.placeholder = @"输入代理AppId";
        textField.text = @"1104466820";
    }];
    [self presentViewController:alert animated:YES completion:nil];
}
#endif

// 查看缓存的token
- (void)viewCachedToken
{
    NSString *token = [[TencentOAuth sharedInstance] getCachedToken];
    NSString *openid = [[TencentOAuth sharedInstance] getCachedOpenID];
    NSDate *exp = [[TencentOAuth sharedInstance] getCachedExpirationDate];
    BOOL isValid = [[TencentOAuth sharedInstance] isCachedTokenValid];
    NSString *str = [NSString stringWithFormat:@"token:%@\nopenid:%@\n 过期时间:%@\n 是否有效:%d",token,openid, exp, isValid];
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"缓存的Token" message:str delegate:nil cancelButtonTitle:@"好的" otherButtonTitles:nil, nil];
    [alertView show];
}

// 删除缓存中的token
- (void)deleteCachedToken
{
    BOOL ret =  [[TencentOAuth sharedInstance] deleteCachedToken];
    NSString *result = [NSString stringWithFormat:@"删除结果：%d", ret];
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"删除缓存的Token" message:result delegate:nil cancelButtonTitle:@"好的" otherButtonTitles:nil, nil];
    [alertView show];
}

// 进入选中的功能对应的控制器
- (void)pushSelectedViewController:(NSNumber *)apiType
{
    UIViewController *rootViewController = nil;
    switch ([apiType unsignedIntegerValue]) {
        case kApiQZone:
        {
            rootViewController = [[QZoneTableViewController alloc] initWithStyle:UITableViewStyleGrouped];
            break;
        }
        case kApiQQ:
        {
            rootViewController = /*[[QQApiDemoController alloc] init]*/[QQApiShareEntry EntryController];
            break;
        }
        case kApiQQqun:
        {
            rootViewController = [QQApiShareEntry QQqunEntryController];
            break;
        }
#if !QQ_OPEN_SDK_LITE
        case kApiQQGroupPro:
        {
            rootViewController = [QuickDialogController controllerForRoot:[QRootElement rootForJSON:@"QQAPI_LaunchGroupPro" withObject:nil]];
            break;
        }
#endif
        case kApiQQFeatures:
        {
            rootViewController = [[FeaturesTableViewController alloc] initWithStyle:UITableViewStyleGrouped];
            break;
        }
        default:
        {
            break;
        }
    }
    [[self navigationController] pushViewController:rootViewController animated:YES];
}

// 请求UnionID
- (void)RequestUnionId {
    BOOL bRet = [[TencentOAuth sharedInstance] RequestUnionId];
    if (!bRet) {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:@"信息不足，请先登录。" delegate:nil cancelButtonTitle:@"好的" otherButtonTitles:nil, nil];
        [alertView show];
    }
}

// 显示当前状态信息
- (void)showDemoAppStatus {
    TencentOAuth *oauth = [TencentOAuth sharedInstance];
    NSString *status = [NSString stringWithFormat:@"AppId: %@\n OpenID: %@\n AccessToken: %@", __TencentDemoAppid_,
                        oauth.openId,
                        oauth.accessToken];
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"状态信息" message:status preferredStyle:(UIAlertControllerStyleAlert)];
    [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:(UIAlertActionStyleCancel) handler:nil]];
    [[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:alert animated:YES completion:nil];
}

// 设置是否同意授权协议
- (void)setIsUserAgreeAhthorization {
    BOOL isUserAgreedAuthorization = [TencentOAuth isUserAgreedAuthorization];
    
    // 更新到SDK中，用户是否同意隐私协议
    [TencentOAuth setIsUserAgreedAuthorization:!isUserAgreedAuthorization];
    
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:QQDemoTableViewSectionOfStatusRowIndexUserAgreeAuthorization inSection:QQDemoTableViewSectionIndexStatus];
    [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
}

- (BOOL)isUserAgreedAuthorization
{
    BOOL isUserAgreedAuthorization = [TencentOAuth isUserAgreedAuthorization];
    return isUserAgreedAuthorization;
}

- (void)logout
{
    [[SDKCall getinstance] logout];
}

- (void)showInvalidTokenOrOpenIDMessage
{
    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"api调用失败" message:@"可能授权已过期，请重新获取" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
    [alert show];
}

#pragma mark - Getter and setter methods

- (NSMutableArray *)getProxyPermissioins {
    return [self getPermissions];
}

- (NSMutableArray *)getPermissions
{
//    NSMutableArray * g_permissions = [[NSMutableArray alloc] initWithObjects:kOPEN_PERMISSION_GET_USER_INFO,
//                                kOPEN_PERMISSION_GET_SIMPLE_USER_INFO,
//                                kOPEN_PERMISSION_ADD_ALBUM,
//                                kOPEN_PERMISSION_ADD_TOPIC,
//                                kOPEN_PERMISSION_CHECK_PAGE_FANS,
//                                kOPEN_PERMISSION_GET_INFO,
//                                kOPEN_PERMISSION_GET_OTHER_INFO,
//                                kOPEN_PERMISSION_LIST_ALBUM,
//                                kOPEN_PERMISSION_UPLOAD_PIC,
//                                kOPEN_PERMISSION_GET_VIP_INFO,
//                                kOPEN_PERMISSION_GET_VIP_RICH_INFO, nil];
    
    NSMutableArray * gg_permissions = [[NSMutableArray alloc] initWithObjects:kOPEN_PERMISSION_ALL, nil];
    
    return gg_permissions;
}

- (UIImageView *)avatarView {
    if (!_avatarView) {
        UIImageView *avatarView = [[UIImageView alloc] init];
        avatarView.frame = CGRectMake(0, 2, 40.0, 40.0);
        avatarView.layer.cornerRadius = avatarView.frame.size.width / 2.0;
        avatarView.layer.masksToBounds = YES;
        _avatarView = avatarView;
    }
    return _avatarView;
}

- (UILabel *)nickLabel {
    if (!_nickLabel) {
        UILabel *nickLabel = [[UILabel alloc] init];
        nickLabel.frame = CGRectMake(54.0, 0, 140.0, 44.0);
        _nickLabel = nickLabel;
    }
    return _nickLabel;
}

@end


#pragma clang diagnostic pop
